import * as R from 'ramda';

import { Button, Dropdown, List, Menu, Modal, Space, Tag } from 'antd';
import React, { Fragment, memo, useCallback, useMemo } from 'react';
import {
  createSyetem,
  deleteSyetem,
  getSyetemDetail,
  getSyetemList,
  updateSyetem,
} from '../../../../service/system';

import AuthButton from '../../../../containers/AuthButton';
import { ButtonEnum } from '../../../../lib/enums';
import Icon from '@/components/Icon';
import ModalConfirmButton from '../../../../components/ModalConfirmButton';
import ProList from '@ant-design/pro-list';
import SystemForm from '../components/SystemForm';
import { SystemIcon } from '../components/SystemIcon';
import classNames from 'classnames';
import { cls } from '../config';
import { unResWrapper } from '../../../../utils/common';
import { useButtonPermission } from '../../../../hooks/permissions';
import useCRUD from '../../../../hooks/useCRUD';
import variables from '../../../../lib/themeVariables';

const SystemList = ({ onChange, curSystem }) => {
  const {
    visible,
    confirmLoading,
    okHandle,
    close,
    form,
    removeHandle,
    isEdit,
    dataSource,
    openHandle,
    loading,
  } = useCRUD({
    listService: (data) =>
      getSyetemList({ page: 1, size: 999, ...data }).then((res) => {
        return res.data.docs;
      }),
    getService: unResWrapper(R.compose(getSyetemDetail, R.prop('id'))),
    updateService: unResWrapper(({ id, ...data }) => updateSyetem(id, data)),
    createService: unResWrapper(createSyetem),
    deleteService: unResWrapper(deleteSyetem),
    autoGetList: true,
    hooks: {
      firstEffect: (data) => {
        const first = data[0];
        if (first) {
          onChange(first);
        }
      },
      listSuccess: (data) => {
        if (!curSystem && data.length) {
          const first = data[0];

          if (first) {
            onChange(first);
          }
        }
      },
      updateSuccess: onChange,
      deleteSuccess: () => onChange(null),
    },
    messages: {
      create: '创建系统成功',
      update: '更新系统成功',
      remove: '删除系统成功',
    },
  });
  const title = useMemo(() => (isEdit ? '编辑系统' : '创建系统'), [isEdit]);
  const { hasRemoveSystemAuthority } = useButtonPermission();
  // console.log(permission);
  const renderItem = useCallback(
    (v) => {
      const code = (
        <Tag style={{ fontSize: 12 }} color={variables.successColor}>
          {v.code}
        </Tag>
      );
      // relative
      return (
        <List.Item
          className={classNames([
            cls('system-list-item'),
            curSystem?.id === v.id && 'active',
          ])}
          onClick={() => onChange(v)}
        >
          <List.Item.Meta
            title={<span style={{ fontSize: 14 }}>{v.name}</span>}
            description={code}
            avatar={<SystemIcon v={v} />}
          />

          <Dropdown
            key="down"
            overlay={
              <Menu>
                <Menu.Item key="edit">
                  <AuthButton
                    code={ButtonEnum.UPDATE_SYSTEM}
                    type="link"
                    onClick={() => openHandle(v)}
                  >
                    编辑
                  </AuthButton>
                </Menu.Item>
                <Menu.Item key="remove">
                  {hasRemoveSystemAuthority && (
                    <ModalConfirmButton
                      text="删除"
                      message={`确定删除系统【${v.name}-${v.code}】`}
                      buttonProps={{ type: 'text', danger: true }}
                      service={() => removeHandle(v)}
                    />
                  )}
                </Menu.Item>
              </Menu>
            }
          >
            <Icon
              className={cls('system-list-item-actions')}
              type="ellipsis-outlined"
            />
          </Dropdown>
        </List.Item>
      );
    },
    [curSystem, onChange, hasRemoveSystemAuthority, openHandle, removeHandle],
  );
  return (
    <Fragment>
      <Modal
        visible={visible}
        confirmLoading={confirmLoading}
        onCancel={close}
        onOk={okHandle}
        title={title}
      >
        <SystemForm form={form} editable={isEdit} />
      </Modal>
      <ProList
        split={true}
        loading={loading}
        className={cls('system-list')}
        renderItem={renderItem}
        headerTitle="系统列表"
        dataSource={dataSource}
        toolBarRender={() => [
          <AuthButton
            code={ButtonEnum.CREATE_SYSTEM}
            type="primary"
            key="create"
            onClick={() => openHandle()}
          >
            新建系统
          </AuthButton>,
        ]}
      />
    </Fragment>
  );
};

export default memo(SystemList);
